package com.ljm.security.util;

import com.ljm.common.constants.SecurityConstants;
import com.ljm.common.constants.SysConstants;
import com.ljm.common.dto.UserInfoDto;
import com.ljm.common.util.SpringBeanUtil;
import com.ljm.security.api.SecurityApi;
import org.apache.commons.lang3.StringUtils;

import java.util.Collections;
import java.util.Set;

/**
 * @author: ChenHuaMing
 * @Date: 2020/6/10 17:31
 * @Description:
 */
public class UserUtil {
    private static SecurityApi securityApi=null;
    /**
     * 获取当前用户
     * @return 用户信息
     */
    public static UserInfoDto getCurUser(){
        String loginName= SysConstants.LOGIN_NAME_TL.get();
        if(StringUtils.isEmpty(loginName)|| SecurityConstants.ROLE_ANNONYMOUS.equals(loginName)){
            return null;
        }else{
            return getSecurityApi().getUserInfo(loginName);
        }
    }

    /**
     * 获取当前登录账号
     * @return 账号
     */
    public static String getLoginName(){
        return SysConstants.LOGIN_NAME_TL.get();
    }

    /**
     * 获取当前用户角色
     * @return 角色信息
     */
    public static Set<String> getRole(){
        String loginName= SysConstants.LOGIN_NAME_TL.get();
        if(StringUtils.isEmpty(loginName)||SecurityConstants.ROLE_ANNONYMOUS.equals(loginName)){
            return Collections.emptySet();
        }else{
            return getSecurityApi().getRole(loginName);
        }
    }

    /**
     * 获取用户权限
     * @return 权限信息
     */
    public static Set<String> getPermission(){
        String loginName= SysConstants.LOGIN_NAME_TL.get();
        if(StringUtils.isEmpty(loginName)||SecurityConstants.ROLE_ANNONYMOUS.equals(loginName)){
            return Collections.emptySet();
        }else{
            return getSecurityApi().getPermission(loginName);
        }
    }

    private static SecurityApi getSecurityApi(){
        if(null==securityApi){
            synchronized (UserUtil.class){
                if(null==securityApi){
                    securityApi= SpringBeanUtil.getBean(SecurityApi.class);
                }
            }
        }
        return securityApi;
    }
}
